﻿using System;
using System.IO;
using System.Net;
using HttpServer;
using HttpListener = HttpServer.HttpListener;
using System.Configuration;

namespace TRConverterServer
{
    class TRServer
    {

        private static HttpListener _listener;
        static WordDocHandler wh;
        static String WEB_ROOT = ConfigurationSettings.AppSettings["WebRoot"];
        static String WEB_PORT = ConfigurationSettings.AppSettings["WebPort"];

        static void Main(string[] args)
        {
            //testing();
            Main2(args);
        }

        static void Main2(string[] args)
        {
            Console.WriteLine("Welcome to Tutorial #1!");
            Console.WriteLine();
            Console.WriteLine("HttpListener allows you to handle everything yourself.");
            Console.WriteLine();
            Console.WriteLine("Browse to http://localhost:8081/hello and http://localhost:8081/goodbye to view the contents");
            wh = new WordDocHandler();
            wh.Init();
            _listener = HttpListener.Create(IPAddress.Any, Convert.ToInt32(WEB_PORT));
            _listener.RequestReceived += OnRequest;
            _listener.Start(5);
            
            Console.ReadLine();
            wh.CleanUp();
            _listener.Stop();
        }

        private static void OnRequest(object source, RequestEventArgs args)
        {
            IHttpClientContext context = (IHttpClientContext)source;
            IHttpRequest request = args.Request;
            HttpParam hp = request.Param;
            //request.g
            // Respond is a small convenience function that let's you send one string to the browser.
            // you can also use the Send, SendHeader and SendBody methods to have total control.
            if (request.Uri.AbsolutePath == "/hello")
                context.Respond("Hello to you too!");

            else if (request.UriParts.Length == 1 && request.UriParts[0] == "goodbye")
            {
                IHttpResponse response = request.CreateResponse(context);
                StreamWriter writer = new StreamWriter(response.Body);
                writer.WriteLine("Goodbye to you too!");
                writer.Flush();
                response.Send();
            }
            else if (true /*hp["url"].Value != null*/)
            {
                //context.Respond(request.QueryString["url"].Value);
                try
                {
                 HttpInputItem inUrl = hp["url"];  //string url = hp["url"].Value;
                //context.Respond(url + " ");
                HttpInputItem hii = hp["type"];
                String url = inUrl.Value;
                String type = (hii.Value == null ? "html" : hii.Value);
                string fileName2 = WEB_ROOT + "/"+ FileNameGen.gen(url) + "." + type;
                //context.Respond("fileName:" + inUrl);
                wh.SaveAs("http://"+ url, ref fileName2, type);
                    context.Respond(inUrl.Value + "..." + fileName2);
                } catch(Exception e)
                {
                    context.Respond("Error: " + e.Message);
                }
                
            }
            else
            {
                //HttpParam hp = request.Param;
                //System.Collections.IEnumerator<HttpInputItem> en = hp.GetEnumerator();
                String s = "";
                foreach (HttpInputItem hit in hp)
                {
                    s += hit.Name + " === " + hit.Value;
                    s += "....." + hp[hit.Name] + "-----"  + (hp["anything"]==null);
                }
                context.Respond(s);
            }
        }


        static void Main1(string[] args)
        {
            wh = new WordDocHandler();
            wh.Init();
            //Console.ReadLine();
            String fileName = "http://www.chikrii.com/products/tex2word/samples/sample.doc";
            string fileName2 = "c:\\temp\\my.html";
            try
            {
                wh.SaveAs(fileName, ref fileName2, "html");
                //context.Respond(fileName2);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.StackTrace);
                Console.WriteLine(e.Message);

                //context.Respond("error" + e.Message);
            }
            Console.ReadLine();
            wh.CleanUp();
        }

        static void testing()
        {
            Microsoft.Office.Interop.Word.Application newApp = new Microsoft.Office.Interop.Word.Application();

            // specifying the Source & Target file names

            object Source = "c:\\temp\\test.doc";

            object Target = "c:\\temp\\test.txt";

            // Use for the parameter whose type are not known or 

            // say Missing

            object Unknown = Type.Missing;

            // Source document open here

            // Additional Parameters are not known so that are 

            // set as a missing type

            newApp.Documents.Open(ref Source, ref Unknown,

            ref Unknown, ref Unknown, ref Unknown,

            ref Unknown, ref Unknown, ref Unknown,

            ref Unknown, ref Unknown, ref Unknown,

            ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown);

            // Specifying the format in which you want the output file 

            object format = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatUnicodeText;

            //Changing the format of the document
            newApp.ActiveDocument.SaveEncoding = Microsoft.Office.Core.MsoEncoding.msoEncodingUnicodeBigEndian;
            object encoding = Microsoft.Office.Core.MsoEncoding.msoEncodingUTF8;
            newApp.ActiveDocument.SaveAs(ref Target, ref format,

            ref Unknown, ref Unknown, ref Unknown,

            ref Unknown, ref Unknown, ref Unknown,

            ref Unknown, ref Unknown, ref Unknown,

            ref encoding, ref Unknown, ref Unknown,

            ref Unknown, ref Unknown);

            // for closing the application

            newApp.Quit(ref Unknown, ref Unknown, ref Unknown);

        }
    }

   

}
